import { question as QuestionApi, paper as PagerApi } from '../../../../../../config/request.js';

module.exports = {
    name: 'pageredit',
    data() {
        return {
            updateBlockInfo: {
                flag: false,
                data: []
            },
            updateFlag: false,
            addBlockDialoge: false,
            /** 题库处理 */
            questions: [],
            selectQuestions: [],
            blockForm: {
                title: '添加题块',
                titles: ['题目列表', '已选题目'],

                name: '',
                questionIds: [],
            },
            blockForm_rules: {
                name: [{ required: true, message: '题块不能为空 ！！', trigger: 'blur' }]
            },

            /** 试卷处理 */
            pager: {
                name: '',
                block: [
                    []
                ],
                remark: '',
                relation: { has_relation: false, relations: [] }
            },
            pager_rules: {
                name: [
                    { required: true, message: '试卷名称不能为空 ！！', trigger: 'blur' }
                ],
                block: [
                    { type: 'array', required: true, message: '试卷内容不能为空 ！！', trigger: 'blur' }
                ]
            },

        }
    },
    methods: {
        /**
         * 用户点击保存模块
         * 
         * @param {any} formName 
         */
        saveBlock(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    const formData = this[formName]
                    const blockData = {}
                    blockData.name = formData.name;
                    blockData.questions = [];
                    blockData.remark = formData.remark;
                    for (let index in formData.questionIds) {
                        const q = this._findQuestion(formData.questionIds[index]);
                        blockData.questions.push(q);
                    }
                    if (this.updateBlockInfo.flag) {
                        Object.assign(this.updateBlockInfo.data, blockData);
                        this.updateBlockInfo.flag = false;
                    } else {
                        this._setBlock(blockData);
                    }
                } else {
                    return false;
                }

                this.$refs[formName].resetFields();
                this.blockForm.questionIds = []
                this.addBlockDialoge = false;
            });
        },
        /**
         * 修改模块信息
         * 
         * @param {any} block 
         */
        updateBlock(block) {
            this.updateBlockInfo.flag = true;
            this.updateBlockInfo.data = block;
            this.blockForm.name = block.name;
            block.questions.forEach(function(question) {
                this.blockForm.questionIds.push(String(question.key));
            }, this);
            this._initQuestionSort();
            this.addBlockDialoge = true;
        },
        /**
         * 设置模块信息
         * 
         * @param {any} blockData 
         */
        _setBlock(blockData) {
            // console.log('_setBlock', this.pager, blockData);
            let insertFlag = false;
            for (let index in this.pager.block) {
                // console.log('for', index, this.pager.block[index], this.pager.block[index].length);
                if (this.pager.block[index].length == 3) {
                    continue;
                } else {
                    this.pager.block[index].push(blockData);
                    insertFlag = true;
                }
            }
            if (!insertFlag) {
                this.pager.block.push([blockData]);
            }
            this._resetQuestionsSort();
            this._setSelectQuestions();
        },
        /**
         * 重置问题排序
         */
        _resetQuestionsSort() {
            this.questions.sort(function(questionA, questionB) {
                // console.log(questionA, questionB);
                return questionA.key - questionB.key;
            });
        },
        /**
         * 根据用户已选题目初始化题目排序
         */
        _initQuestionSort() {
            this.blockForm.questionIds.forEach(function(key) {
                this._updateIndex(key);
            }, this);
        },

        /**
         * 设置被编辑进试卷的题目信息
         */
        _setSelectQuestions() {
            var selectQuestions = [];
            // console.log('block', this.pager.block)
            this.pager.block.forEach(function(blocks) {
                blocks.forEach(function(block) {
                    block.questions.forEach(function(question) {
                        var children = [];
                        if (question.type >= 4) {
                            let label = { 4: '问答题', 5: '选择日期', 6: '选择时间', 7: '选择数字' }[question.type];
                            children.push({ value: -1, key: -1, label: label });
                        } else {
                            // console.log('options', question.options)
                            var options = JSON.parse(question.options);
                            // console.log('options', options)
                            options.forEach(function(option) {
                                children.push({ value: Number(option.id), key: Number(option.id), label: option.value });
                            }, this);
                        }
                        selectQuestions.push({
                            key: Number(question.key),
                            value: Number(question.key),
                            label: question.label,
                            children: children
                        })
                    }, this);
                }, this);
            }, this);
            this.selectQuestions = selectQuestions;
            // console.log('selectQuestions', this.selectQuestions);
        },
        _initSelectQuestions() {
            // console.log('this.pager.block.', this.pager.block)
            this._setSelectQuestions();
        },
        /**
         * 通过id找问题
         * 
         * @param {any} questionId 
         * @returns 
         */
        _findQuestion(questionId) {
            for (let index in this.questions) {
                if (this.questions[index].key == questionId) {
                    return this.questions[index];
                }
            }
        },
        //初始化问题
        _initQuestion() {

            QuestionApi.queryAll.call(this, (data) => {
                let _q = data.questions;
                let questData = [];
                for (let index in _q) {
                    questData.push({
                        key: Number(_q[index].id),
                        label: _q[index].main,
                        options: _q[index].options,
                        type: _q[index].type
                    });
                }

                this.questions = questData;
                // console.log(data);
                if (this.updateFlag) {
                    this._getPagerData();
                }
            })
        },
        /**
         * 穿梭栏事件
         * 
         * @param {any} value 选中的key数组
         * @param {any} direction 试卷 left左移动 right右移
         * @param {any} movedKeys 移动的key数组
         */
        handleChange(value, direction, movedKeys) {
            var that = this;
            movedKeys.forEach(function(key) {
                this._updateIndex(key);
            }, this);
        },
        /**
         * 根据key更新题目位置
         * @param {any} key 
         */
        _updateIndex(key) {
            let obj = this.findBykey(key);
            this.questions.splice(this.questions.indexOf(obj), 1);
            this.questions.push(obj);
        },
        /**
         * 通过key找到问题对象
         * 
         * @param {any} key 
         * @returns 
         */
        findBykey(key) {
            for (let i in this.questions) {
                if (key == this.questions[i].key) {
                    return this.questions[i];
                }
            }
        },
        /**
         * 保存试卷
         * 
         * @param {any} formName 
         */
        savePager(formName) {
            // console.log('savePager', this[formName]);
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    const formData = this[formName];

                    const pagerData = {};
                    pagerData.name = formData.name;
                    pagerData.block = formData.block;
                    pagerData.remark = formData.remark;
                    pagerData.relation = formData.relation;
                    this._setPager(pagerData);
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        /**
         * 设置试卷信息
         * 
         * @param {any} pagerData 
         */
        _setPager(pagerData) {
            var block = [];
            // console.log('block', pagerData.block)
            pagerData.block.forEach(function(blocks) {
                blocks.forEach(function(data) {
                    var questionId = [];
                    block.push({ "name": data.name, "questionId": questionId });
                    // console.log('block', block);
                    data.questions.forEach(function(question) {
                        questionId.push(Number(question.key));
                    }, this)

                }, this);
            }, this);
            // console.log(block);
            var id = this.$route.query.id;
            var options = {
                block: block,
                name: pagerData.name,
                remark: pagerData.remark,
                relation: pagerData.relation
            };
            if (this.updateFlag) {
                Object.assign(options, { id: id });
                this._updatePager(options);
            } else {
                this._createPager(options);
            }
        },
        /**
         * 创建试卷
         * 
         * @param {any} options 
         */
        _createPager(options) {
            PagerApi.createQuestion.call(this, options, data => {
                // console.log(data);
                this.$router.push('/business/template/papers');
            })
        },
        /**
         * 更新试卷
         * 
         * @param {any} options 
         */
        _updatePager(options) {
            PagerApi.updateQuestion.call(this, options, data => {
                // console.log(data);
                this.$router.push('/business/template/papers');
            })
        },
        /**
         * 重置试卷表单
         * 
         * @param {any} formName 
         */
        resetPager(formName) {
            this.$refs[formName].resetFields();
        },
        /**
         * 获取试卷数据
         * 
         */
        _getPagerData() {
            var id = this.$route.query.id;
            // console.log('----id----', id);
            PagerApi.queryById.call(this, id, data => {
                // console.log('----_getPagerData', data);
                this._initFrom(data);
            });
        },
        /**
         * 初始化表单
         * 
         * @param {any} data 
         */
        _initFrom(data) {
            // console.log('data', data, 'data')
            this.pager.name = data.paper.name;
            this.pager.remark = data.paper.remark;
            var blockArray = [];

            var blocks = JSON.parse(data.paper.block);
            for (var i in blocks) {
                var array;
                if (Number(i) % 3 == 0) {
                    array = [];
                    blockArray.push(array);
                } else {
                    array = blockArray[Number.parseInt((Number(i) / 3))];
                }
                const blockObject = { name: '', questions: [] };
                blockObject.name = blocks[i].name;
                blocks[i].questionId.forEach(id => {
                    // console.log(this._findQuestion(id), ' this._findQuestion(id)')
                    blockObject.questions.push(this._findQuestion(id));
                });
                array.push(blockObject);
            }
            this.pager.block = blockArray;
            // console.log("relation", data.paper.relation);
            this.pager.relation = JSON.parse(data.paper.relation);
            // console.log("relation", this.pager.relation);

            this._initSelectQuestions();
        },
        /**
         * 添加关联
         * 
         */
        addRelation() {
            this.pager.relation.relations.push({ next_id: '', pre_ids: [] });
        },
        /**
         * 删除关联
         * 
         * @param {any} index 
         */
        deletRelation(index) {
            this.pager.relation.relations.splice(index, 1);
        }
    },
    mounted() {
        this.updateFlag = false;
        if (this.$route.query.id) {
            this.updateFlag = true;
        }
        this._initQuestion();

    }
}